#!/usr/bin/env python3
"""
FastMCP Multi-Service 直接测试脚本
无需 MCP 配置，直接测试服务功能
"""

import sys
import json
import time
from datetime import datetime

# 模拟服务函数（如果无法导入实际服务）
def mock_translate(msg: str, output_type: str = "json"):
    """模拟翻译服务"""
    translations = {
        "Hello World": "你好世界",
        "你好世界": "Hello World", 
        "Good morning": "早上好",
        "谢谢": "Thank you",
        "How are you?": "你好吗？"
    }
    
    result = translations.get(msg, f"翻译结果: {msg}")
    
    if output_type == "json":
        return {
            "original": msg,
            "translated": result,
            "source_lang": "auto",
            "target_lang": "auto",
            "timestamp": datetime.now().isoformat()
        }
    else:
        return result

def mock_get_weather(city: str, output_type: str = "json"):
    """模拟天气服务"""
    weather_data = {
        "北京": {"weather": "晴", "temperature": "25°C", "humidity": "60%"},
        "上海": {"weather": "多云", "temperature": "23°C", "humidity": "70%"},
        "广州": {"weather": "雨", "temperature": "28°C", "humidity": "80%"},
        "深圳": {"weather": "晴", "temperature": "29°C", "humidity": "65%"}
    }
    
    data = weather_data.get(city, {"weather": "未知", "temperature": "N/A", "humidity": "N/A"})
    
    if output_type == "json":
        return {
            "city": city,
            **data,
            "timestamp": datetime.now().isoformat()
        }
    else:
        return f"{city}: {data['weather']}, {data['temperature']}, 湿度{data['humidity']}"

def mock_get_gold_price(output_type: str = "json"):
    """模拟黄金价格服务"""
    import random
    price = round(1950 + random.uniform(-50, 50), 2)
    
    if output_type == "json":
        return {
            "gold_price": str(price),
            "unit": "USD/oz",
            "change": f"+{random.uniform(-5, 5):.2f}",
            "timestamp": datetime.now().isoformat()
        }
    else:
        return f"黄金价格: ${price}/盎司"

# 尝试导入真实服务
try:
    from main import translate, get_weather, get_gold_price, service_status
    USE_REAL_SERVICES = True
    print("✅ 成功导入真实服务")
except ImportError:
    print("⚠️  无法导入真实服务，将使用模拟数据")
    translate = mock_translate
    get_weather = mock_get_weather
    get_gold_price = mock_get_gold_price
    USE_REAL_SERVICES = False

def print_header(title):
    """打印测试标题"""
    print("\n" + "="*60)
    print(f"🧪 {title}")
    print("="*60)

def print_test_result(test_name, input_data, result, success=True):
    """打印测试结果"""
    status = "✅" if success else "❌"
    print(f"\n{status} {test_name}")
    print(f"输入: {input_data}")
    
    if isinstance(result, dict):
        print(f"结果: {json.dumps(result, ensure_ascii=False, indent=2)}")
    else:
        print(f"结果: {result}")
    print("-" * 40)

def test_translation_service():
    """测试翻译服务"""
    print_header("翻译服务测试")
    
    test_cases = [
        ("Hello World", "json"),
        ("你好世界", "json"), 
        ("Good morning", "text"),
        ("谢谢", "text"),
        ("How are you?", "json")
    ]
    
    for msg, output_type in test_cases:
        try:
            result = translate(msg, output_type)
            success = result is not None and not (isinstance(result, dict) and "error" in result)
            print_test_result(f"翻译测试 ({output_type})", f"'{msg}'", result, success)
            time.sleep(0.5)  # 避免请求过快
        except Exception as e:
            print_test_result(f"翻译测试 ({output_type})", f"'{msg}'", f"错误: {e}", False)

def test_weather_service():
    """测试天气服务"""
    print_header("天气查询服务测试")
    
    test_cities = [
        ("北京", "json"),
        ("上海", "json"),
        ("广州", "text"), 
        ("深圳", "text"),
        ("杭州", "json")
    ]
    
    for city, output_type in test_cities:
        try:
            result = get_weather(city, output_type)
            success = result is not None and not (isinstance(result, dict) and "error" in result)
            print_test_result(f"天气查询 ({output_type})", f"'{city}'", result, success)
            time.sleep(0.5)
        except Exception as e:
            print_test_result(f"天气查询 ({output_type})", f"'{city}'", f"错误: {e}", False)

def test_gold_price_service():
    """测试黄金价格服务"""
    print_header("黄金价格查询服务测试")
    
    test_formats = ["json", "text"]
    
    for output_type in test_formats:
        try:
            result = get_gold_price(output_type)
            success = result is not None and not (isinstance(result, dict) and "error" in result)
            print_test_result(f"黄金价格查询 ({output_type})", "当前金价", result, success)
            time.sleep(0.5)
        except Exception as e:
            print_test_result(f"黄金价格查询 ({output_type})", "当前金价", f"错误: {e}", False)

def test_service_status():
    """测试服务状态"""
    if not USE_REAL_SERVICES:
        print_header("服务状态检查 (跳过 - 使用模拟数据)")
        return
        
    print_header("服务状态检查")
    
    try:
        result = service_status()
        print_test_result("服务状态检查", "所有服务", result, True)
    except Exception as e:
        print_test_result("服务状态检查", "所有服务", f"错误: {e}", False)

def interactive_test():
    """交互式测试"""
    print_header("交互式测试")
    
    while True:
        print("\n请选择要测试的服务:")
        print("1. 翻译服务")
        print("2. 天气查询")
        print("3. 黄金价格查询")
        print("4. 退出")
        
        choice = input("输入选择 (1-4): ").strip()
        
        if choice == "1":
            msg = input("请输入要翻译的文本: ").strip()
            output_type = input("输出格式 (json/text, 默认json): ").strip() or "json"
            
            try:
                result = translate(msg, output_type)
                print_test_result("交互式翻译", f"'{msg}' ({output_type})", result)
            except Exception as e:
                print(f"❌ 翻译失败: {e}")
                
        elif choice == "2":
            city = input("请输入城市名: ").strip()
            output_type = input("输出格式 (json/text, 默认json): ").strip() or "json"
            
            try:
                result = get_weather(city, output_type)
                print_test_result("交互式天气查询", f"'{city}' ({output_type})", result)
            except Exception as e:
                print(f"❌ 天气查询失败: {e}")
                
        elif choice == "3":
            output_type = input("输出格式 (json/text, 默认json): ").strip() or "json"
            
            try:
                result = get_gold_price(output_type)
                print_test_result("交互式金价查询", f"当前金价 ({output_type})", result)
            except Exception as e:
                print(f"❌ 金价查询失败: {e}")
                
        elif choice == "4":
            print("👋 退出交互式测试")
            break
        else:
            print("❌ 无效选择，请重新输入")

def benchmark_test():
    """性能基准测试"""
    print_header("性能基准测试")
    
    # 测试翻译服务性能
    print("🏃‍♂️ 翻译服务性能测试...")
    start_time = time.time()
    
    for i in range(5):
        try:
            translate("Hello", "json")
            print(f"  请求 {i+1}/5 完成")
        except:
            print(f"  请求 {i+1}/5 失败")
            
    end_time = time.time()
    avg_time = (end_time - start_time) / 5
    print(f"平均响应时间: {avg_time:.2f}秒")
    
    # 测试天气服务性能
    print("\n🌤️  天气服务性能测试...")
    start_time = time.time()
    
    cities = ["北京", "上海", "广州", "深圳", "杭州"]
    for city in cities:
        try:
            get_weather(city, "json")
            print(f"  查询 {city} 完成")
        except:
            print(f"  查询 {city} 失败")
            
    end_time = time.time()
    avg_time = (end_time - start_time) / 5
    print(f"平均响应时间: {avg_time:.2f}秒")

def main():
    """主函数"""
    print("🚀 FastMCP Multi-Service 直接测试工具")
    print(f"⏰ 测试时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"🔧 服务模式: {'真实服务' if USE_REAL_SERVICES else '模拟数据'}")
    
    if not USE_REAL_SERVICES:
        print("\n💡 提示: 将 main.py 放在同目录下可测试真实服务")
    
    while True:
        print("\n" + "="*60)
        print("请选择测试模式:")
        print("1. 完整自动测试")
        print("2. 翻译服务测试")
        print("3. 天气服务测试") 
        print("4. 黄金价格服务测试")
        print("5. 服务状态测试")
        print